/* eslint-disable react/destructuring-assignment */
import React, { Component } from 'react';
import moment from 'moment';
import { Card, Row, Col, Input, List,Upload, Button, message,Modal, Spin } from 'antd';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { withRouter } from 'dva/router';
import { connect } from 'dva';
import downloadFile,{ requestHeadersMd5  } from '@/utils/utils';
import { UploadOutlined } from '@ant-design/icons';

import queryString from 'query-string';
import DescriptionList from '@/components/DescriptionList';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
// import TextOverFlow from '../../TextOverFlow';

const FormItem = Form.Item;
const { Description } = DescriptionList;
const { TextArea } = Input;
@Form.create()
@connect(({ problempage: { proObjList, probTypeList, proDetail, btnFlag }, loading, login }) => ({
  proObjList,
  probTypeList,
  proDetail,
  btnFlag,
  loading: loading.effects['problempage/getDetail'],
  baseUser: login.baseUser,
}))
class ProDetail extends Component {
  state = {
    affixList: [],
    fdAffixIds:[],
    fileList:[],
    uploadUrl: '/csApi/fileServer/uploadFile',
    downloadUrl: '/csApi/fileServer/downloadFile',
  };

  componentDidMount() {
    const { location, dispatch } = this.props;
    const { busiType, probDetId } = queryString.parse(location.search);
    dispatch({
      type: 'problempage/updateModalData',
      payload: {
        btnFlag: false,
      },
    });
    this.setState({
      busiType,
      probDetId,
    });
    this.getDetail(busiType, probDetId);
  }

  // 获取详情
  getDetail = (busiType, probDetId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'problempage/getDetail',
      payload: {
        busiType,
        probDetId,
      },
    });
  };

    // 文件上传
    changeUpload = (info, listContFile) => {
      const { downloadUrl, fdAffixIds} = this.state;
      let { fileList } = info;
      this.setState({ fileList });
      const { file } = info;
      const newData = listContFile.map(item => ({ ...item }));
      if (file.status === 'done' && file.response.success) {
        const fileId = file.response.data.split('|')[0];
        const fileName = file.response.data.split('|')[1];
        fileList.map(files => {
          const temp = files;
          temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
          temp.linkProps = { download: `${fileName}` };
        });
        newData.push({
          uid: file.uid,
          affixId: fileId,
          affixName: fileName,
        });
        this.setState({ affixList: newData });
        this.setState({ fdAffixIds: newData });

        message.success('文件上传成功！');
      } else {
        fileList = [];
        if ((file.status === 'done' && !file.response.success) || file.status === 'error') {
          message.error('上传失败！');
        }
        return fileList;
      }
    };
  

    // 移除文件
    removeFile = (file, listContFile) => {
      // const { affixIds} = this.state;
      const newData = listContFile.filter(item => item.uid !== file.uid);
      this.setState({ affixList: newData });
      this.setState({ fdAffixIds :newData});
    };

    // 文件限制大小
    beforeUpload = () => {};

  // 关闭
  onClose = () => {
    window.history.back();
  };

  // 反馈
  proFeedBack = () => {
    const {
      form: { validateFields },
      dispatch,
      form,
    } = this.props;
    const { busiType, probDetId ,fdAffixIds,affixList} = this.state;
 
    validateFields((err, values) => {
      const obj = values;
      delete obj.fdAffixIds;
      if (!err) {
        if (fdAffixIds.length) {
          fdAffixIds.map(f => {
            const ff = f;
            delete ff.uid;
          });
        }
        dispatch({
          type: 'problempage/addProbFdbk',
          payload: {
            ...values,
            fdAffixIds,
            busiType,
            probDetId,
          },
        }).then(res => {
          if (res.success) {
            this.fileList=[]
            this.setState({ fdAffixIds: [], affixList:[],fileList:[]});
            form.resetFields();
            this.getDetail(busiType, probDetId);
          }
        });
      }
    });
  };

  // 反馈并取消标记
  cancelSign = () => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    const { busiType, probDetId,fdAffixIds } = this.state;
    validateFields((err, values,) => {
      const obj = values;
      delete obj.fdAffixIds;
      if (!err) {
        if (fdAffixIds.length) {
          fdAffixIds.map(f => {
            const ff = f;
            delete ff.uid;
          });
        }
        Modal.confirm({
          title: '提示',
          content: '确认取消标记吗？',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            dispatch({
              type: 'problempage/cancelSign',
              payload: {
                ...values,
                busiType,
                fdAffixIds,
                probDetId,
              },
            }).then(res => {
              this.fileList=[]
              this.setState({ fdAffixIds: [], affixList:[],fileList:[]});
              if (res.success) {
                window.history.back();
              }
            });
          },
          onCancel() {},
        });
      }
    });
  };

  // 修改
  modifyData = () => {
    const { onModifyData = () => {}, proDetail } = this.props;
    onModifyData(proDetail);
  };

  // 查看详情
  goDetail = () => {
    const { onViewDetails = () => {}, proDetail } = this.props;
    onViewDetails(proDetail);
  };

  render() {
    const {
      form: { getFieldDecorator },
      proDetail,
      isNotModify,
      isNotFeedback,
      btnFlag,
      loading,
    } = this.props;
    const { uploadUrl, affixList,fileList } = this.state;
    const uploadProps = {
      beforeUpload: info => this.beforeUpload(info, affixList),
      action: uploadUrl,
      fileList,
      headers: requestHeadersMd5(),
      onChange: info => this.changeUpload(info, affixList),
      onRemove: file => this.removeFile(file, affixList),
    };
    return (
      <Spin tip="loading..." spinning={loading}>
        <Card
          title="问题人员"
          style={{ border: '0px', marginBottom: 24, fontSize: 16, color: '#262626' }}
        >
          <Form>
            <DescriptionList style={{ marginBottom: 24 }}>
              <Description term="姓名">{proDetail.empName || '--'}</Description>
              <Description term="证件号">{proDetail.certNo || '--'}</Description>
              <Description term="电话">{proDetail.phone ? proDetail.phone : '--'}</Description>
            </DescriptionList>
            <DescriptionList style={{ marginBottom: 24 }}>
              <Description term="是否联系员工">{proDetail.contEmpFlagName || '--'}</Description>
              <Description term="客户">{proDetail.custName || '--'}</Description>
              <Description term="执行地">{proDetail.areaName || '--'}</Description>
            </DescriptionList>
            <DescriptionList style={{ marginBottom: 24 }}>
              <Description term="提醒对象">{proDetail.alrtObjName || '--'}</Description>
              <Description term="问题对象">{proDetail.probObjName || '--'}</Description>
              <Description term="问题类型">{proDetail.probTypeName || '--'}</Description>
            </DescriptionList>
            <DescriptionList style={{ marginBottom: 24 }}>
              <Description term="所属客服">{proDetail.blngCsName || '--'}</Description>
              <Description term="提出人">{proDetail.creName || '--'}</Description>
              <Description term="提出时间">
                {moment(proDetail.creTime).format('YYYY-MM-DD HH:mm')}
              </Description>
            </DescriptionList>
            <DescriptionList col={1} style={{ wordBreak: 'break-all',marginBottom: 24 }}> 
              <Description term="问题说明">
                {proDetail.probTypeDesc || '--'}
              </Description>
            </DescriptionList>
            <DescriptionList col={1} style={{ wordBreak: 'break-all' ,marginBottom: 24 }}>
              <Description term="问题附件">
                {proDetail.affixIds && proDetail.affixIds.length
                ? proDetail.affixIds.map(item => (
                  <Row key={item.affixId} style={{ marginRight: 30 }}>
                    <a
                      onClick={e => {
                        e.preventDefault();
                        downloadFile({ fileId: item.affixId, fileName: item.affixName });
                      }}
                    >
                      {item.affixName || '--'}
                    </a>
                  </Row>
                ))
                : null}
              </Description>
            </DescriptionList>
            
          </Form>
          <Row gutter={64}>
            {!isNotFeedback && (
              <Col xl={{ span: 16 }} lg={{ span: 16 }} md={{ span: 16 }} sm={24}>
                <FormItem label="反馈" className={styles.addInfoStyle}>
                  {getFieldDecorator('content', {
                    initialValue: '',
                    rules: [{ required: true, message: '请输入反馈内容' }],
                  })(<TextArea placeholder="请输入反馈内容" maxLength={3000} />)}
                </FormItem>
              </Col>
            )}
          </Row>
          <Row>
            {!isNotFeedback && (
              <Col xl={{ span: 16 }} lg={{ span: 16 }} md={{ span: 16 }} sm={24}>
                <Form.Item label="附件" className={styles.addInfoStyle}>
                  {getFieldDecorator('fdAffixIds', {
                    rules: [{ required: false, message: '请输入' }],
                  })(
                    <Upload {...uploadProps} beforeUpload={this.beforeUpload}>
                      {affixList.length < 5 ? (
                        <Button>
                          <UploadOutlined /> 上传附件
                        </Button>
                      ) : null}
                    </Upload>
                  )}
                </Form.Item>
              </Col>
            )}
          </Row>
          <div>
            <h4 style={{ marginTop: `${isNotFeedback && '24px'}` }}>反馈记录</h4>
            <List
              itemLayout="horizontal"
              split={false}
              dataSource={proDetail.probFdbks || []}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    // avatar={<Avatar src={userAvatar} />}
                    title={
                      <div>
                        <span>{item.creName}</span>
                        {/* <span style={{ marginLeft: 20 }}>{item.role}</span> */}
                      </div>
                    }
                    description={
                      <div>
                        <div>
                          <p style={{ wordBreak: 'break-all',marginBottom:0 }}> {item.content}</p>
                        </div>
                        <div>
                          {item.fdAffixIds && item.fdAffixIds.length
                          ? item.fdAffixIds.map(i => (
                            <Row key={i.affixId} style={{ marginRight: 30 }}>
                              <a
                                onClick={e => {
                                  e.preventDefault();
                                  downloadFile({ fileId: i.affixId, fileName: i.affixName });
                                }}
                              >
                                {i.affixName || '--'}
                              </a>
                            </Row>
                          ))
                          : null}
                        </div>
                        <p style={{marginTop:8}}>{moment(item.creTime).format('YYYY-MM-DD HH:mm')}</p>
                      </div>
                     
                    }
                  />
                </List.Item>
              )}
            />
          </div>
          <p style={{ textAlign: 'center', marginTop: 32 }}>
            <Button style={{ marginRight: 10 }} onClick={this.onClose}>
              返回
            </Button>
            <Button disabled={btnFlag} style={{ marginRight: 10 }} onClick={this.goDetail}>
              查看详情
            </Button>
            {!isNotModify && (
              <Authorized
                // authority={[
                //   'cs:ordAddProb:updateBusiData',
                //   'cs:ordDeduProb:updateBusiData',
                //   'cs:ordAdjProb:updateBusiData',
                //   'cs:wageProb:updateBusiData',
                //   'cs:insHdlProb:updateBusiData',
                //   'cs:accuHdlProb:updateBusiData',
                //   'es:entryProb:updateBusiData',
                //   'es:rsgnProb:updateBusiData',
                //   'business:insHdlProb:updateBusiData',
                //   'business:accuHdlProb:updateBusiData',
                //   'es:rcrdHdlProb:updateBusiData',
                //   'os:insAddProb:updateBusiData',
                //   'os:insDeduProb:updateBusiData',
                //   'os:insAdjProb:updateBusiData',
                //   'os:accuAddProb:updateBusiData',
                //   'os:accuDeduProb:updateBusiData',
                //   'os:accuAdjProb:updateBusiData',
                //   'os:rcrcHdlProb:updateBusiData',
                //   'ns:sndrAddProb:updateBusiData',
                //   'ns:sndrDeduProb:updateBusiData',
                //   'ns:sndrAdjProb:updateBusiData',
                //   'ns:rcvrAddProb:updateBusiData',
                //   'ns:rcvrDeduProb:updateBusiData',
                //   'ns:rcvrAdjProb:updateBusiData',
                //   'ns:sndrWageProb:updateBusiData',
                //   'ns:rcvrWageProb:updateBusiData',
                //   'ns:sndrInsHdlProb:updateBusiData',
                //   'ns:rcvrInsHdlProb:updateBusiData',
                // ]}
                noMatch={null}
              >
                {(proDetail && proDetail.operFlag === 1 && (
                  <Button disabled={btnFlag} style={{ marginRight: 10 }} onClick={this.modifyData}>
                    修改业务数据
                  </Button>
                )) ||
                  null}
              </Authorized>
            )}
            {!isNotFeedback && (
              <React.Fragment>
                <Authorized
                  authority={[
                    'cs:ordAddProb:addProbFdbk',
                    'cs:ordDeduProb:addProbFdbk',
                    'cs:ordAdjProb:addProbFdbk',
                    'cs:wageProb:addProbFdbk',
                    'cs:insHdlProb:addProbFdbk',
                    'cs:accuHdlProb:addProbFdbk',
                    'es:entryProb:addProbFdbk',
                    'es:rsgnProb:addProbFdbk',
                    'business:insHdlProb:addProbFdbk',
                    'business:accuHdlProb:addProbFdbk',
                    'es:rcrdHdlProb:addProbFdbk',
                    'os:insAddProb:addProbFdbk',
                    'os:insDeduProb:addProbFdbk',
                    'os:insAdjProb:addProbFdbk',
                    'os:accuAddProb:addProbFdbk',
                    'os:accuDeduProb:addProbFdbk',
                    'os:accuAdjProb:addProbFdbk',
                    'os:rcrcHdlProb:addProbFdbk',
                    'ns:sndrAddProb:addProbFdbk',
                    'ns:sndrDeduProb:addProbFdbk',
                    'ns:sndrAdjProb:addProbFdbk',
                    'ns:rcvrAddProb:addProbFdbk',
                    'ns:rcvrDeduProb:addProbFdbk',
                    'ns:rcvrAdjProb:addProbFdbk',
                    'ns:sndrWageProb:addProbFdbk',
                    'ns:rcvrWageProb:addProbFdbk',
                    'ns:sndrInsHdlProb:addProbFdbk',
                    'ns:rcvrInsHdlProb:addProbFdbk',
                  ]}
                  noMatch={null}
                >
                  <Button
                    disabled={btnFlag}
                    type="primary"
                    style={{ marginRight: 10 }}
                    onClick={this.proFeedBack}
                  >
                    反馈
                  </Button>
                </Authorized>
                <Authorized
                  authority={[
                    'cs:ordAddProb:addProbFdbk',
                    'cs:ordDeduProb:addProbFdbk',
                    'cs:ordAdjProb:addProbFdbk',
                    'cs:wageProb:addProbFdbk',
                    'cs:insHdlProb:addProbFdbk',
                    'cs:accuHdlProb:addProbFdbk',
                    'es:entryProb:addProbFdbk',
                    'es:rsgnProb:addProbFdbk',
                    'business:insHdlProb:addProbFdbk',
                    'business:accuHdlProb:addProbFdbk',
                    'es:rcrdHdlProb:addProbFdbk',
                    'os:insAddProb:addProbFdbk',
                    'os:insDeduProb:addProbFdbk',
                    'os:insAdjProb:addProbFdbk',
                    'os:accuAddProb:addProbFdbk',
                    'os:accuDeduProb:addProbFdbk',
                    'os:accuAdjProb:addProbFdbk',
                    'os:rcrcHdlProb:addProbFdbk',
                    'ns:sndrAddProb:addProbFdbk',
                    'ns:sndrDeduProb:addProbFdbk',
                    'ns:sndrAdjProb:addProbFdbk',
                    'ns:rcvrAddProb:addProbFdbk',
                    'ns:rcvrDeduProb:addProbFdbk',
                    'ns:rcvrAdjProb:addProbFdbk',
                    'ns:sndrWageProb:addProbFdbk',
                    'ns:rcvrWageProb:addProbFdbk',
                    'ns:sndrInsHdlProb:addProbFdbk',
                    'ns:rcvrInsHdlProb:addProbFdbk',
                  ]}
                  noMatch={null}
                >
                  <Button
                    disabled={btnFlag}
                    type="primary"
                    style={{ marginRight: 10 }}
                    onClick={this.cancelSign}
                  >
                    反馈并取消标记
                  </Button>
                </Authorized>
              </React.Fragment>
            )}
          </p>
        </Card>
      </Spin>
    );
  }
}
export default withRouter(ProDetail);
